var currentRunningVideoID = -1;
var currentRunningEmbeddedID = -1;
var isTabBeingPaused = false;

window.setTimeout(function () { 


//alert("hi");
//html5, embeds
var videos = document.getElementsByTagName("video");
var embeds = document.getElementsByTagName("embed");

for (var i = 0, video; video = videos[i]; i++) {
	video.setAttribute('videoid', i);
	video.addEventListener('play', playing, false);
	video.addEventListener('pause', pausing, false);
}

for (var i = 0, embed; embed = embeds[i]; i++) {
	embed.setAttribute('embeddedid', i);
	embed.addEventListener('Play', playing, false);
	embed.addEventListener('Stop', pausing, false);
}

function playing() {
	console.log("playing!");
	currentRunningVideoID = this.getAttribute('videoid');
	currentRunningEmbeddedID = this.getAttribute('embeddedid');
	isTabBeingPaused = true;
	chrome.extension.sendRequest({}, function(response) {});
}

function pausing() {
	console.log("pausing");
	currentRunningVideoID = -1;
	currentRunningEmbeddedID = -1;
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {

 if (videos.length != document.getElementsByTagName("video").length || embeds.length != document.getElementsByTagName("embed").length) {
	console.assert(false);
	alert("videos and/or embedded videos not counted properly");
}


 if (request.action == "pauseVideo") {
  for (var i = 0, video; video = videos[i]; i++) {
	if (!isTabBeingPaused || currentRunningVideoID != i) {
		video.pause();
	}
	else {
		isTabBeingPaused = false;
		console.log(isTabBeingPaused);
	}
  }
  for (var i=0, embed; embed = embeds[i]; i++) {
	try {
		if (!isTabBeingPaused || currentRunningEmbeddedID != i) {
			embed.pause();
		}
		else {
			isTabBeingPaused = false;
			console.log(isTabBeingPaused);
		}
	}
	catch(err) {
        }
  }
 }
 else {
  //no action necessary here!
 }

 sendResponse({}); // Send nothing..

});
}, 0);
